package summer.hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution15 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) return res;
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int m = i + 1;
            int n = nums.length - 1;
            while (m < n) {
                int cur = nums[i] + nums[m] + nums[n];
                if (cur == 0) {
                    ArrayList<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[m]);
                    tmp.add(nums[n]);
                    res.add(tmp);
                    while (m < n && nums[m] == nums[m + 1]) m++;
                    while (n > m && nums[n] == nums[n - 1]) n--;
                    m++;
                    n--;
                } else if (cur > 0) n--;
                else m++;
            }
        }
        return res;
    }
}
